package application.threads;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.ConcurrentModificationException;
import java.util.List;

import javax.servlet.http.HttpSession;

import model.person.Person;
import model.person.notification.MyNotification;
import dao.MyDAO;

public class NotificationScanner extends Thread {

	private MyDAO dao;
	
	private Calendar calendar;

	private List<HttpSession> listOfSessions = new ArrayList<>();

	public NotificationScanner() {
		super();
		setName("Notification Scanner");
	}

	public void setDao(MyDAO dao) {
		this.dao = dao;
	}

	public void addToList(HttpSession session) {
		listOfSessions.add(session);
	}

	private boolean removeFromList(HttpSession session) {
		return listOfSessions.remove(session);
	}

	public boolean hasSession(HttpSession session) {
		return listOfSessions.contains(session);
	}

	@Override
	public void run() {
		int timer = 0;
		while (true) {
			try {
				timer++;
				calendar=null;
				for (HttpSession session : listOfSessions) {
					try {
						if(timer%45==0){
							if(calendar==null){
								calendar=Calendar.getInstance();
								timer=1;
							}
							if(calendar.getTimeInMillis()-session.getLastAccessedTime()>=90000){
								session.invalidate();
							}
						}
						Person loggedUser = (Person) session.getAttribute("loggedUser");
						List<MyNotification> listOfNotifications = dao.getAllEntitiesWhere(MyNotification.class, "id_to", "" + loggedUser.getAccountID());
						session.setAttribute("listOfNotifications", listOfNotifications);
					} catch (IllegalStateException e) {
						System.out.println("Logout");
						removeFromList(session);
					}
				}
			} catch (ConcurrentModificationException e) {
				// e.printStackTrace();
			}	try {
				sleep(1000);
			} catch (InterruptedException e) {
				// System.err.println(e);
				// e.printStackTrace();
			}
		}
	}
}
